package logic

import (
	"context"
	"errors"
	"house/cache"
	"house/models"

	"house/houserpc/houserpc"
	"house/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForGetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForGetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForGetPasswordLogic {
	return &ForGetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ForGetPasswordLogic) ForGetPassword(in *houserpc.ForGetPasswordRequest) (*houserpc.ForGetPasswordResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	models.DB.Where("mobile=?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, errors.New("手机号不存在请重新输入")
	}
	data, _ := cache.Rdb.Get(l.ctx, "send"+in.Mobile).Result()
	if in.SendSmsCode != data {
		return nil, errors.New("短信验证码错误请重新输入")
	}
	if in.Password != in.NewPassword {
		return nil, errors.New("两次密码输入不一致重新输入")
	}
	if user.Password == in.Password {
		return nil, errors.New("新密码与旧密码一致请重新输入")
	}
	user.Password = in.Password
	models.DB.Updates(user)
	return &houserpc.ForGetPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
